package com.woniu.zsd.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.zsd.user.entity.Address;
import com.woniu.zsd.user.mapper.AddressMapper;
import com.woniu.zsd.user.param.AddAddressParam;
import com.woniu.zsd.user.service.AddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yjf
 * @since 2025年02月22日
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Resource
    private AddressMapper addressMapper;
    @Override
    public List<Address> selectAddressByUserId(Integer userId) {
        //根据id查询user存储的所有地址
        if (userId != null) {
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",userId);
            return addressMapper.selectList(queryWrapper);
        }
        throw new RuntimeException("用户id为空");
    }

    @Override
    public void addAddress(AddAddressParam param) {
        Address address = new Address();
        address.setUserId(param.getUserId());
        address.setCity(param.getCity());
        address.setDistrict(param.getDistrict());
        address.setStreet(param.getStreet());
        address.setDetailedAddress(param.getDetail());
        address.setLatitude(new BigDecimal(param.getLat()));
        address.setLongitude(new BigDecimal(param.getLng()));
        //当isDefault为1时说明当前的地址为默认地址，取消其他默认地址
        if (param.getIsDefault() == 1) {
            QueryWrapper<Address> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id",param.getUserId());
            queryWrapper.eq("is_default",1);
            List<Address> list = addressMapper.selectList(queryWrapper);
            if (!list.isEmpty()) {
                Address beforeAddress = list.get(0);
                beforeAddress.setIsDefault(0);
                addressMapper.updateById(beforeAddress);
            }
        }
        address.setIsDefault(param.getIsDefault());
        addressMapper.insert(address);
    }
}
